package controller

import (
	"fmt"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	// _ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	//"github.com/astaxie/beego/server/web"
)

type ShopController struct {
	beego.Controller
	//web.Controller
}

type ShopConfig struct {
	RedisAddr string
	RedisPort string

	DbDriver   string
	DbUser     string
	DbPwd      string
	DbHost     string
	DbPort     string
	DbDatabase string
	DbProtocol string

	TablePre string
}

var (
	shopConfig    = &ShopConfig{}
	Db            *sqlx.DB
	err           error
	category      []Category
	limit         int                    // 显示多少条记录
	executeResult map[string]interface{} //执行结果
	result        sql.Result
	lastInsertId  int64
)

// 将所有功能，包括模型，结构体混合在同一文件当中，自己来拆分成真正的web框架的结构
type Category struct {
	Id      int    `db:"id" json:"id"`
	Tid     int    `db:"tid" json:"tid"`
	Name    string `db:"name" json:"name"`
	Addtime int    `db:"addtime" json:"addtime"`
	Intro   string `db:"intro" json:"intro"`
	Preview string `db:"preview" json:"preview"`
	Sort    string `db:"sort" json:"sort"`
}

func InitAppConfig() *ShopConfig {
	redisAddr := beego.AppConfig.String("redis_addr")
	redisPort := beego.AppConfig.String("redis_port")
	dbDriver := beego.AppConfig.String("db_driver")
	dbUser := beego.AppConfig.String("db_user")
	dbPwd := beego.AppConfig.String("db_pwd")
	dbHost := beego.AppConfig.String("db_host")
	dbPort := beego.AppConfig.String("db_port")
	dbDatabase := beego.AppConfig.String("db_database")
	dbProtocol := beego.AppConfig.String("db_protocol")

	tablePre := beego.AppConfig.String("table_pre")

	//redisAddr, _ := web.AppConfig.String("redis_addr")
	//redisPort, _ := web.AppConfig.String("redis_port")
	//dbDriver, _ := web.AppConfig.String("db_driver")
	//dbUser, _ := web.AppConfig.String("db_user")
	//dbPwd, _ := web.AppConfig.String("db_pwd")
	//dbHost, _ := web.AppConfig.String("db_host")
	//dbPort, _ := web.AppConfig.String("db_port")
	//dbDatabase, _ := web.AppConfig.String("db_database")
	//dbProtocol, _ := web.AppConfig.String("db_protocol")

	shopConfig.RedisAddr = redisAddr
	shopConfig.RedisPort = redisPort
	shopConfig.DbDriver = dbDriver
	shopConfig.DbUser = dbUser
	shopConfig.DbPwd = dbPwd
	shopConfig.DbHost = dbHost
	shopConfig.DbPort = dbPort
	shopConfig.DbDatabase = dbDatabase
	shopConfig.DbProtocol = dbProtocol

	shopConfig.TablePre = tablePre
	return shopConfig
}

func init() {
	InitAppConfig()
	//sqlPrameter := fmt.Sprintf("%s:%s@%s(%s:%d)/%s", shopConfig.DbUser, shopConfig.DbPwd, shopConfig.DbProtocol, shopConfig.DbHost, shopConfig.DbPort, shopConfig.DbDatabase)
	sqlPrameter := fmt.Sprintf("%s:%s@%s(%s:%s)/%s", shopConfig.DbUser, shopConfig.DbPwd, shopConfig.DbProtocol, shopConfig.DbHost, shopConfig.DbPort, shopConfig.DbDatabase)
	//sqlx.Open(shopConfig.DbDriver, "root:root@tcp(1.1.1.1.:3306)/databasename")
	if Db, err = sqlx.Open(shopConfig.DbDriver, sqlPrameter); err != nil {
		logs.Debug("数据库连接失败,失败原因：", err.Error())
		return
	}

}

// 通过sqlx操作mysql,crud
func (this *ShopController) GetProduct() {
	//{
	//	"status":1,
	//	"msg":"xxx",
	//	"data":xxx
	//}
	executeResult = make(map[string]interface{})
	//executeResult["status"] = 1
	//executeResult["msg"] = "操作成功"
	//executeResult["data"] = []string{"hello","world"}
	//{
	//	"status":1,
	//	"msg":"操作成功",
	//	"data":{"hello","world"}
	//}
	//beego当中输出json
	//this.Data["json"] = executeResult
	//this.ServeJSON()
	//return

	/*
		获取变量当中参数
		this.GetInt()
		this.GetString()
		this.GetFloat()
		this.GetBool()

	*/

	// url当中的数据
	// 请求体当中的数据
	// http://localhost/xxx/xx/?limit=100
	if limit, err = this.GetInt("limit", 10); err != nil {
		//logs.Debug("this.GetInt err:", err.Error())
		executeResult["status"] = 0
		executeResult["msg"] = err.Error()
		executeResult["data"] = nil
		this.Data["json"] = executeResult
		this.ServeJSON()
		return
	}

	// 1.使用之前赋值为nil
	category = nil

	// 2.定义成局部变量
	//var category []Category
	// sqlx操作mysql-查询
	// Db.Select(&category, "select id, name, intro, preview from "+shopConfig.TablePre+"category limit ?", limit)
	if err = Db.Select(&category, "select id, name, intro, preview from category limit ?", limit); err != nil {
		//logs.Debug("Db.Select err:", err.Error())
		executeResult["status"] = 0
		executeResult["msg"] = err.Error()
		executeResult["data"] = nil
		this.Data["json"] = executeResult
		this.ServeJSON()
		return
	}

	//beego当中输出json
	if len(category) > 0 {
		executeResult["status"] = 1
		executeResult["msg"] = "查询数据库成功"
		executeResult["data"] = category
	} else {
		executeResult["status"] = 0
		executeResult["msg"] = "查询数据库失败"
		executeResult["data"] = category
	}

	// sqlx操作mysql-添加
	if result, err = Db.Exec("insert into category(`name`, `intro`, `preview`) values (?, ?, ?)", "手机", "oppo Reno手机超炫", "11111111"); err != nil {
		executeResult["status"] = 0
		executeResult["msg"] = "数据库插入失败,原因：" + err.Error()
		executeResult["data"] = nil
	} else {
		if lastInsertId, err = result.LastInsertId(); err != nil {
			executeResult["status"] = 0
			executeResult["msg"] = "操作失败"
		} else {
			executeResult["status"] = 1
			executeResult["msg"] = "操作成功"
			executeResult["data"] = lastInsertId
		}
	}

	// sqlx操作mysql-修改
	Db.Exec("delete from category where id = ?", 1)

	// sqlx操作mysql-更新
	Db.Exec("update category set key = value where id = ? and xx = ?", 1, 123)

	// 输出json
	this.Data["json"] = executeResult
	this.ServeJSON()
	return

}

func (this *ShopController) TestBeego() {
	var names []string = []string{"imooc", "涛哥", "golang"}
	this.Data["json"] = names

	this.ServeJSON()
}
